#include "mainwindow.h"
#include <QTimer>
#include <QPainter>
#include <QPixmap>
#include <QKeyEvent>
#include <QDebug>
#include "draw_thread.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle(tr("打砖块"));
    timer = new QTimer(this);
    m_bGameStatus = true;
    initGame();
    connect(timer, SIGNAL(timeout()), this, SLOT(run()));
    int times = 10;
    timer->start(times);
    resize(800,800);
}

MainWindow::~MainWindow()
{

}

void MainWindow::initGame()
{
    CBall ball;
    ball.setHeght(20);
    ball.setWidth(20);
    ball.setPostion(400,400);
    m_level.balls.push_back(ball);

    CBaffle baffle;
    baffle.setHeght(20);
    baffle.setWidth(200);
    baffle.setPostion(5,800-100);
    m_level.baffle = baffle;

    CScore score;
    score.setPostion(800-100,100);
    m_level.score = score;


    for (int i = 0 ; i < 4;i++) {
        for(int j = 0 ; j < 4 ; j++){
            int x = 170*i;
            int y = 30*j;

            CBlock block;
            block.setHeght(20);
            block.setWidth(160);
            block.setPostion(x,y);
            m_level.blocks.push_back(block);

        }
    }

    //m_vectOldPix.size();

}

void MainWindow::initBackgroud()
{

}

void MainWindow::run()
{
    update();
    m_level.run();
}

void MainWindow::paintEvent(QPaintEvent *event)
{


    QPixmap tempPix(size());
    QPainter painterCache(&tempPix);
    QPainter painter(this);
    // 画背景
    painterCache.setBrush(Qt::black);
    painterCache.drawRect(0, 0, size().width(), size().height());
    m_level.paint(&painterCache);

    double time_Start = (double)clock();
    //painter.drawPixmap(0, 0, tempPix);
    GDrawThread t(&painter,&tempPix);
    t.start();
    t.wait();
    double end_Start = (double)clock();

    qInfo()<<time_Start-end_Start;
    QWidget::paintEvent(event);
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{

        switch (event->key())
        {
        case Qt::Key_Space:
           // m_bGameStatus *= -1;
             if(m_bGameStatus)
            {
                timer->stop();
                m_bGameStatus = false;
            }else {
               timer->start(1);
               m_bGameStatus = true;
            }
            break;
        case Qt::Key_Left:
                m_level.baffle.moveLeft();
                 break;

        case Qt::Key_Right:
                    m_level.baffle.moveRight();
                 break;
        }

        QWidget::keyPressEvent(event);
}
